﻿var app = new Vue({
    el: '#app',
    data: {
        loading: false,
        Index: 0,
        selectedProduct: null,
        stockModel: {
            productId: 0,
            description: "Size",
            count: 10
        },
        products: []
    },
    mounted() {
        this.getStocks();
    },
    methods: {
        getStocks() {
            this.loading = true;
            axios.get('/API/stock')
                .then(res => {
                    this.products = res.data
                })
                .catch(err => {
                    console.log(err);
                })
                .then(() => {
                    this.loading = false;
                })
        },
        selectProduct(product) {
            this.selectedProduct = product;
            this.stockModel.productId = product.id
        },
        updateStock() {
            this.loading = true;
            axios.put('/API/stock/', {
                stocks: this.selectedProduct.stocks.map(x => {
                    return {
                        id: x.id,
                        description: x.description,
                        count: x.count,
                        productId: this.selectedProduct.id
                    };
                })
            })
                .then(res => {
                    this.selectedProduct.stocks.splice(index, 1);
                })
                .catch(err => {
                    console.log(err);
                })
                .then(() => {
                    this.loading = false;
                })
        },
        deleteStock(id, index) {
            this.loading = true;
            axios.delete('/API/stock/' + id)
                .then(res => {
                    this.selectedProduct.stocks.splice(index, 1);
                })
                .catch(err => {
                    console.log(err);
                })
                .then(() => {
                    this.loading = false;
                })
        },
        addStock() {
            this.loading = true;
            axios.post('/API/stock', this.stockModel)
                .then(res => {
                    this.selectedProduct.stocks.push(res.data);
                })
                .catch(err => {
                    console.log(err);
                })
                .then(() => {
                    this.loading = false;
                })
        }
    }
})